{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "bf87e29d",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\u001b[33mWARNING: Ignoring invalid distribution -umpy (/Users/richmondalake/miniconda3/envs/memorizz/lib/python3.9/site-packages)\u001b[0m\u001b[33m\n",
      "\u001b[0m\u001b[33mWARNING: Ignoring invalid distribution -umpy (/Users/richmondalake/miniconda3/envs/memorizz/lib/python3.9/site-packages)\u001b[0m\u001b[33m\n",
      "\u001b[0m\u001b[33mWARNING: Ignoring invalid distribution -umpy (/Users/richmondalake/miniconda3/envs/memorizz/lib/python3.9/site-packages)\u001b[0m\u001b[33m\n",
      "\u001b[0m"
     ]
    }
   ],
   "source": [
    "! pip install -qU yahooquery"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ddc8887c",
   "metadata": {},
   "outputs": [],
   "source": [
    "import getpass\n",
    "import os\n",
    "\n",
    "# Function to securely get and set environment variables\n",
    "def set_env_securely(var_name, prompt):\n",
    "    value = getpass.getpass(prompt)\n",
    "    os.environ[var_name] = value"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "30c18ebb",
   "metadata": {},
   "outputs": [],
   "source": [
    "set_env_securely(\"MONGODB_URI\", \"Enter your MongoDB URI: \")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c2e14279",
   "metadata": {},
   "outputs": [],
   "source": [
    "set_env_securely(\"OPENAI_API_KEY\", \"Enter your OpenAI API key: \")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2fa62798",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Vector search index 'vector_index' already exists for collection personas.\n",
      "Vector search index 'vector_index' already exists for collection toolbox.\n",
      "Vector search index 'vector_index' already exists for collection short_term_memory.\n",
      "Vector search index 'vector_index' already exists for collection long_term_memory.\n",
      "Vector search index 'vector_index' already exists for collection conversation_memory.\n",
      "Vector search index 'vector_index' already exists for collection workflow_memory.\n",
      "Vector search index 'vector_index' already exists for collection agents.\n",
      "Vector search index 'vector_index' already exists for collection shared_memory.\n",
      "Vector search index 'vector_index' already exists for collection summaries.\n"
     ]
    }
   ],
   "source": [
    "from memorizz.memory_provider.mongodb.provider import MongoDBConfig, MongoDBProvider\n",
    "\n",
    "# Create a memory provider\n",
    "mongodb_config = MongoDBConfig(uri=os.environ[\"MONGODB_URI\"])\n",
    "memory_provider = MongoDBProvider(mongodb_config)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "dc158050",
   "metadata": {},
   "outputs": [],
   "source": [
    "from memorizz.persona import Persona, RoleType\n",
    "\n",
    "# Create a persona for our agent\n",
    "persona = Persona(\n",
    "    name=\"Alex\",\n",
    "    role=RoleType.ASSISTANT,\n",
    "    goals=\"Help users learn and provide thoughtful assistance\",\n",
    "    background=\"An AI assistant focused on being helpful, educational, and adaptive\"\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c976c474",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Using application mode 'assistant' with memory types: ['conversation_memory', 'long_term_memory', 'personas', 'short_term_memory', 'summaries']\n"
     ]
    }
   ],
   "source": [
    "from memorizz.memagent import MemAgent\n",
    "from memorizz.llms.openai import OpenAI\n",
    "\n",
    "# Create an agent with the persona\n",
    "agent = MemAgent(\n",
    "    model=OpenAI(model=\"gpt-4\"),\n",
    "    persona=persona,\n",
    "    instruction=\"You are a helpful learning assistant that adapts based on interactions\",\n",
    "    application_mode=\"assistant\",\n",
    "    memory_provider=memory_provider\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "8593d98a",
   "metadata": {},
   "outputs": [],
   "source": [
    "agent.save()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "id": "553d7378",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Created agent: 686a70bf2152354a7b3086c2\n",
      "Initial persona goals: Assist users by offering timely and personalized support. Help users learn and provide thoughtful assistance\n",
      "Initial persona background: An assistant agent crafted to manage schedules, answer queries, and help with daily tasks. An AI assistant focused on being helpful, educational, and adaptive\n"
     ]
    }
   ],
   "source": [
    "print(f\"Created agent: {agent.agent_id}\")\n",
    "print(f\"Initial persona goals: {agent.persona.goals}\")\n",
    "print(f\"Initial persona background: {agent.persona.background}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "c0ba8a0b",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "--- Simulating user interactions ---\n"
     ]
    }
   ],
   "source": [
    "# Simulate some interactions to create memory components\n",
    "print(\"\\n--- Simulating user interactions ---\")\n",
    "interactions = [\n",
    "    \"Can you help me understand machine learning?\",\n",
    "    \"I'm struggling with Python programming concepts\",\n",
    "    \"What are the best practices for data visualization?\", \n",
    "    \"How do I improve my debugging skills?\",\n",
    "    \"Can you explain neural networks in simple terms?\",\n",
    "    \"I need help with statistical analysis\",\n",
    "    \"What's the difference between supervised and unsupervised learning?\",\n",
    "    \"How do I handle missing data in datasets?\",\n",
    "    \"Can you recommend learning resources for data science?\",\n",
    "    \"I'm working on a classification problem and need guidance\"\n",
    "]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "df6f0048",
   "metadata": {},
   "outputs": [],
   "source": [
    "import time\n",
    "\n",
    "# Process interactions to build up memory\n",
    "for i, query in enumerate(interactions):\n",
    "    print(f\"Processing interaction {i+1}: {query[:50]}...\")\n",
    "    response = agent.run(query)\n",
    "    print(f\"  Response: {response[:100]}...\")\n",
    "    \n",
    "    # Add a small delay to create time separation\n",
    "    time.sleep(1)\n",
    "\n",
    "print(f\"\\nAgent now has {len(agent.memory_ids)} memory sessions\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "61a26399",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Generate summaries from the accumulated memories\n",
    "print(\"\\n--- Generating Summaries ---\")\n",
    "summary_ids = agent.generate_summaries(\n",
    "    days_back=1,  # Look back 1 day (covers all our interactions)\n",
    "    max_memories_per_summary=5  # Smaller chunks for demo\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "id": "94e89797",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Generated 4 summaries:\n",
      "  Summary 1: 686a71bd2152354a7b3086e2\n",
      "  Summary 2: 686a71c82152354a7b3086e3\n",
      "  Summary 3: 686a71d62152354a7b3086e4\n",
      "  Summary 4: 686a71de2152354a7b3086e5\n"
     ]
    }
   ],
   "source": [
    "print(f\"Generated {len(summary_ids)} summaries:\")\n",
    "for i, summary_id in enumerate(summary_ids):\n",
    "    print(f\"  Summary {i+1}: {summary_id}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "9259a93f",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "--- Examining Summaries ---\n",
      "Sample summary content:\n",
      "  Raw period_start: 2025-07-06T13:49:04.628287 (type: <class 'str'>)\n",
      "  Raw period_end: 2025-07-06T13:49:38.703359 (type: <class 'str'>)\n",
      "  Period: 2025-07-06 13:49:04.628287 to 2025-07-06 13:49:38.703359\n",
      "  Memory components: 5\n",
      "  Content: The user seeks knowledge expansion in several domains namely Machine Learning (ML), Python programming, and data visualization.\n",
      "\n",
      "The user first asked about Machine Learning, and they were provided wit...\n"
     ]
    }
   ],
   "source": [
    "from datetime import datetime\n",
    "from memorizz.memory_provider.memory_type import MemoryType\n",
    "\n",
    "# Show what the summaries look like\n",
    "print(\"\\n--- Examining Summaries ---\")\n",
    "if summary_ids:\n",
    "    # Get the first summary to show its content\n",
    "    summary = memory_provider.retrieve_by_id(summary_ids[0], MemoryType.SUMMARIES)\n",
    "    if summary:\n",
    "        print(f\"Sample summary content:\")\n",
    "        \n",
    "        # Debug: Check what format the timestamps are in\n",
    "        print(f\"  Raw period_start: {summary['period_start']} (type: {type(summary['period_start'])})\")\n",
    "        print(f\"  Raw period_end: {summary['period_end']} (type: {type(summary['period_end'])})\")\n",
    "        \n",
    "        # Try to parse timestamps (handle both numeric strings and ISO format)\n",
    "        try:\n",
    "            # If they're numeric strings, convert to float first\n",
    "            start_time = float(summary['period_start'])\n",
    "            end_time = float(summary['period_end'])\n",
    "            start_dt = datetime.fromtimestamp(start_time)\n",
    "            end_dt = datetime.fromtimestamp(end_time)\n",
    "            print(f\"  Period: {start_dt} to {end_dt}\")\n",
    "        except ValueError:\n",
    "            # If they're ISO format strings, parse directly\n",
    "            try:\n",
    "                start_dt = datetime.fromisoformat(summary['period_start'])\n",
    "                end_dt = datetime.fromisoformat(summary['period_end'])\n",
    "                print(f\"  Period: {start_dt} to {end_dt}\")\n",
    "            except ValueError:\n",
    "                # If neither works, just show the raw values\n",
    "                print(f\"  Period: {summary['period_start']} to {summary['period_end']} (unknown format)\")\n",
    "        \n",
    "        print(f\"  Memory components: {summary['memory_components_count']}\")\n",
    "        print(f\"  Content: {summary['summary_content'][:200]}...\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "id": "9d29fb64",
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "INFO:src.memorizz.memagent:Updating persona for agent 686a70bf2152354a7b3086c2 using 3 summaries\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "--- Updating Persona from Summaries ---\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "INFO:src.memorizz.memagent:Successfully updated and saved persona for agent 686a70bf2152354a7b3086c2\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Storing persona: Alex in the memory provider, in the personas collection\n"
     ]
    }
   ],
   "source": [
    "# Update persona based on summaries\n",
    "print(\"\\n--- Updating Persona from Summaries ---\")\n",
    "persona_updated = agent.update_persona_from_summaries(\n",
    "    max_summaries=3,  # Use up to 3 most recent summaries\n",
    "    save=True         # Save the updated persona\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "id": "59f69f8b",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "✅ Persona successfully updated!\n",
      "Updated goals: Continuing to educate users on various aspects of data science, including statistical analysis, machine learning, data visualization, and debugging in programming. Assist in practical problem-solving items. Stay adaptive, thoughtful, and personalized in providing support, while expanding ability to guide users through complex data-related projects.\n",
      "Updated background: An evolved AI assistant skilled in providing comprehensive guidance on data science, machine learning and neural networks, with experience in handling practical problems related to data cleansing and debugging code. Maintains a focus on educating users and aiding their growth in technical knowledge, demonstrating an ability to adapt and provide clarity on complex topics and real-life scenarios.\n",
      "\n",
      "--- Persona Evolution ---\n",
      "The persona has evolved based on interaction patterns:\n",
      "- Goals may now reflect educational focus\n",
      "- Background may include experience with technical questions\n",
      "- The agent has adapted to user needs over time\n",
      "\n",
      "--- Summary Retrieval Examples ---\n"
     ]
    }
   ],
   "source": [
    "if persona_updated:\n",
    "    print(\"✅ Persona successfully updated!\")\n",
    "    print(f\"Updated goals: {agent.persona.goals}\")\n",
    "    print(f\"Updated background: {agent.persona.background}\")\n",
    "    \n",
    "    # Show the differences\n",
    "    print(\"\\n--- Persona Evolution ---\")\n",
    "    print(\"The persona has evolved based on interaction patterns:\")\n",
    "    print(\"- Goals may now reflect educational focus\")\n",
    "    print(\"- Background may include experience with technical questions\")\n",
    "    print(\"- The agent has adapted to user needs over time\")\n",
    "else:\n",
    "    print(\"❌ Persona update failed\")\n",
    "\n",
    "# Demonstrate retrieval of summaries\n",
    "print(\"\\n--- Summary Retrieval Examples ---\")\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "id": "f6151490",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Found 4 summaries for memory_id 686a70bf2152354a7b3086c3\n",
      "Found 0 summaries in the last 24 hours\n"
     ]
    }
   ],
   "source": [
    "# Get all summaries for this agent\n",
    "if agent.memory_ids:\n",
    "    memory_id = agent.memory_ids[0]\n",
    "    all_summaries = memory_provider.get_summaries_by_memory_id(memory_id, limit=10)\n",
    "    print(f\"Found {len(all_summaries)} summaries for memory_id {memory_id}\")\n",
    "    \n",
    "    # Get summaries within a time range\n",
    "    current_time = time.time()\n",
    "    start_time = current_time - (24 * 60 * 60)  # Last 24 hours\n",
    "    time_range_summaries = memory_provider.get_summaries_by_time_range(\n",
    "        memory_id, start_time, current_time\n",
    "    )\n",
    "    print(f\"Found {len(time_range_summaries)} summaries in the last 24 hours\")\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "67991ed2",
   "metadata": {},
   "outputs": [],
   "source": [
    "agent.save()\n",
    "print(f\"\\nAgent saved with ID: {agent.agent_id}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "29a03a8f",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "memorizz",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.19"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
